package example;

import com.alibaba.fastjson2.JSON;
import com.easyaop.api.Arounds;
import com.easyaop.api.advisor.MethodPointcut;
import com.easyaop.core.AroundsImpl;
import ognl.Ognl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;

public class Watch {
    static Writer writer;

    static {
        try {
            writer = new FileWriter(new File("watch.log"));
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        //        watch classname METHOD {el}
        String className = args[0];
        String methodName = args[1];
        String el = args[2];

        Arounds arounds= AroundsImpl.getInstance();
        arounds.add(new MethodPointcut(className,methodName,"(..)")
                ,(the,argArr,join,method)->{
                    Object result = method.call();
                    HashMap root = new HashMap();
                    root.put("params",argArr);
                    root.put("returnObj",result);
                    Object log = Ognl.getValue(el, root);
                    String jsonString = JSON.toJSONString(log);
                    writer.write(jsonString);
                    writer.flush();
                    return result;

                });
    }
}
